use serde_json::json;
use std::io::{self, BufRead, BufReader};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

pub fn collect_shutdown_start_times() -> Result<serde_json::Value, io::Error> {
    // 获取系统ID
    let system_id = get_system_id();

    // PowerShell 命令和事件处理
    let mut child_30_42 = Command::new("powershell")
        .arg("Get-WinEvent -FilterHashtable @{LogName='System'; ID=@(42, 30, 6005, 6006)} | Where-Object { $_.TimeCreated -ge (Get-Date).Date } | Select-Object TimeCreated, Id")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap_or_else(|e| {
            eprintln!("Failed to execute PowerShell command for 30, 42 events.");
            std::process::exit(1);
        });

    let stdout_30_42 = match child_30_42.stdout.take() {
        Some(stdout) => stdout,
        None => {
            eprintln!("Failed to capture stdout for 30, 42 events.");
            return Ok(json!({ "systemId": system_id, "record": [] }));
        }
    };

    let reader_30_42 = BufReader::new(stdout_30_42);
    let timeout = Duration::new(30, 0);
    let start_time = Instant::now();
    let mut records = Vec::new();

    for line in reader_30_42.lines() {
        match line {
            Ok(line) => {
                if start_time.elapsed() > timeout {
                    eprintln!("Timeout exceeded while reading 30, 42 events.");
                    break;
                }

                if line.contains("TimeCreated") || line.contains("---") {
                    continue;
                }

                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 {
                    let time_created = parts[..parts.len() - 1].join(" ");
                    let id = parts[parts.len() - 1].to_string();
                    records.push(json!({ "id": id, "timeCreated": time_created }));
                }
            }
            Err(e) => {
                eprintln!("Error reading line for 30, 42 events: {}", e);
                // 跳过这行，什么都不添加
                continue;
            }
        }
    }

    let mut child_4800_4801 = Command::new("powershell")
        .arg("Get-WinEvent -FilterHashtable @{LogName='Security'; ID=@(4800, 4801)} | Where-Object { $_.TimeCreated -ge (Get-Date).Date } | Select-Object TimeCreated, Id")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap_or_else(|e| {
            eprintln!("Failed to execute PowerShell command for 4800, 4801 events.");
            std::process::exit(1);
        });

    let stdout_4800_4801 = match child_4800_4801.stdout.take() {
        Some(stdout) => stdout,
        None => {
            eprintln!("Failed to capture stdout for 4800, 4801 events.");
            return Ok(json!({ "systemId": system_id, "record": records }));
        }
    };

    let reader_4800_4801 = BufReader::new(stdout_4800_4801);

    for line in reader_4800_4801.lines() {
        match line {
            Ok(line) => {
                if start_time.elapsed() > timeout {
                    eprintln!("Timeout exceeded while reading 4800, 4801 events.");
                    break;
                }

                if line.contains("TimeCreated") || line.contains("---") {
                    continue;
                }

                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 {
                    let time_created = parts[..parts.len() - 1].join(" ");
                    let id = parts[parts.len() - 1].to_string();
                    records.push(json!({ "id": id, "timeCreated": time_created }));
                }
            }
            Err(e) => {
                eprintln!("Error reading line for 4800, 4801 events: {}", e);
                // 跳过这行，什么都不添加
                continue;
            }
        }
    }

    // 创建最终的 JSON 对象
    let result = json!({
        "systemId": system_id,
        "record": records
    });

    Ok(result)
}

fn get_system_id() -> String {
    let output = Command::new("wmic")
        .arg("csproduct")
        .arg("get")
        .arg("UUID")
        .output();

    match output {
        Ok(output) => {
            let output_str = String::from_utf8_lossy(&output.stdout);
            output_str
                .lines()
                .skip(1) // 跳过第一行（标题）
                .filter(|&line| !line.trim().is_empty()) // 过滤空行
                .next()
                .unwrap_or("Unknown")
                .trim()
                .to_string()
        }
        Err(e) => {
            eprintln!("Failed to execute wmic command: {}", e);
            "Unknown".to_string()
        }
    }
}
